<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Api\Repositories\WxContRepositories;
use App\Models\WxChat;
use App\Models\WxUser;
use Illuminate\Http\Request;

class ChatController extends BaseController
{

    /**
     * 用户发起聊天
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addChat(Request $request)
    {

        $uid = $request->uid;
        $oid = $request->oid;
        $chat_content = $request->input('chat_content', '');
        $chat_image = $request->input('chat_image', '');

        return $this->success(WxContRepositories::add($uid, $oid, $chat_content, $chat_image));
    }

    /**
     * 查询用户聊天记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserChat(Request $request, $limit = 6)
    {

        $uid = $request->uid;
        $oid = $request->oid;

        $data = WxChat::where(function ($query) use ($uid, $oid) {
            $query->where('user_id', $uid)
                ->where('object_id', $oid);
        })
            ->orWhere(function ($query) use ($uid, $oid) {
                $query->where('user_id', $oid)
                    ->where('object_id', $uid);
            })
            ->orderByRaw('id DESC')
            ->simplePaginate($limit);

        $data->map(function ($v) {
            $imgList = array();
            array_push($imgList, ['img_url' => $v->chat_image]);
            $v->imgList = $imgList;
            $v->user = WxUser::where('id', $v->user_id)->first();
            $v->datetime = format_datetime($v->created_at);
            return $v;
        });

        return $this->success($data);
    }

    /**
     * 已读对应用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readUserChat(Request $request)
    {
        $uid = $request->uid;
        $oid = $request->oid;

        $data = WxChat::where(function ($query) use ($uid, $oid) {
            $query->where('user_id', $oid)
                ->where('object_id', $uid);
        })
            ->update(['is_read' => 1]);

        return $this->success($data);
    }


    /**
     * 用户删除聊天记录
     */
    public function userDelMessage(Request $request)
    {
        $uid = $request->uid;
        $userid = $request->userid;


        $data = WxChat::where(function ($query) use ($uid, $userid) {
            $query->where('user_id', $uid)
                ->where('object_id', $userid);
        })
            ->orWhere(function ($query) use ($uid, $userid) {
                $query->where('user_id', $userid)
                    ->where('object_id', $uid);
            })->update(['chat_state' => 1]);

        return $this->success($data);
    }
}
